let time =
  let start = Unix.gettimeofday () in
  fun () -> Unix.gettimeofday () -. start

let rec get_colors z = function
  | [] -> (0.,0.,0.)
  | (alt,color)::l when alt = z -> color
  | e::l -> get_colors z l

let draw_face vertices get_color = function
  | (a,b,c) -> GlDraw.color (get_colors (c-1) Data.alt_color_list);
               GlDraw.vertex3 (vertices.(a-1));
               GlDraw.vertex3 (vertices.(b-1));
               GlDraw.vertex3 (vertices.(c-1))
  | _ -> failwith "face incomplete"

let draw_faces vertices l colors =
  Array.iter (draw_face vertices get_color) l

let draw () =
  GlClear.clear [ `color; `depth ];
  GlMat.mode `modelview;
  GlMat.load_identity ();
  GluMat.look_at (3.,4.,2.) (0.,0.,0.) (0.,0.,1.);
  GlMat.rotate ~angle:(400. *. Sys.time ()) ~x:0. ~y:0. ~z:1. ();
  GlDraw.begins `triangles;

  draw_faces [|(1., 0., 0.),(0., 0., 1.),(0., 1., 0.),(0., 0., 0.)|] 
    [(1,2,3),(1,3,4),(2,3,4),(2,1,4)] 
    [|(1.,0.,0.),(0.,1.,0.),(0.,0.,1.),(0.6,0.4,0.2)|];


(*
  GlDraw.color (1.,0.,0.);
  GlDraw.vertex3 (1., 0., 0.);
  GlDraw.vertex3 (0., 0., 1.);
  GlDraw.vertex3 (0., 1., 0.);

  GlDraw.color (0.,1.,0.);
  GlDraw.vertex3 (1., 0., 0.);
  GlDraw.vertex3 (0., 1., 0.);
  GlDraw.vertex3 (0., 0., 0.);

  GlDraw.color (0.,0.,1.);
  GlDraw.vertex3 (0., 0., 1.);
  GlDraw.vertex3 (0., 1., 0.);
  GlDraw.vertex3 (0., 0., 0.);

  GlDraw.color (0.6, 0.4, 0.2);
  GlDraw.vertex3 (0., 0., 1.);
  GlDraw.vertex3 (1., 0., 0.);
  GlDraw.vertex3 (0., 0., 0.);
 *)
  GlDraw.ends ();
  Gl.flush ();
  Glut.swapBuffers ()

let main () =
  ignore( Glut.init Sys.argv );
  Glut.initDisplayMode ~double_buffer:true ~depth:true ();
  Glut.initWindowSize 640 480;
  ignore (Glut.createWindow ~title:"3D");
  GlMat.mode `projection;
  GlMat.load_identity ();
  GluMat.perspective ~fovy:70. ~aspect:(640. /. 480.) ~z:(1., 1000.);
  Gl.enable `depth_test;

(*    GlDraw.begins `triangles;
    List.iter GlDraw.vertex3 [1., 1., 1.; 0., 1., 1.; 0., 0., 1.];
    GlDraw.ends ();
    Glut.swapBuffers ()
  in
  GlMat.mode `modelview; 
  Glut.displayFunc ~cb:render; *)

  Glut.displayFunc ~cb:draw;
  Glut.idleFunc ~cb:(Some Glut.postRedisplay);
  Glut.mainLoop ()

let _ = main ()
